# apps/devices/models.py

from django.db import models
from django.db.models.signals import post_migrate
from django.dispatch import receiver
from apps.rooms.models import Room   # 新增

class Device(models.Model):
    device_id      = models.AutoField(primary_key=True)
    device_name    = models.CharField(max_length=255)
    device_type    = models.CharField(max_length=100)
    room           = models.ForeignKey(Room, null=True, blank=True,
                                       on_delete=models.SET_NULL, db_column="room_id")
    status         = models.CharField(max_length=50, default="offline")
    control_value  = models.IntegerField(null=True, blank=True)

    class Meta:
        db_table = "devices"

    def __str__(self):
        return self.device_name


# ---------- 初始化设备 ----------
@receiver(post_migrate)
def create_initial_devices(sender, **kwargs):
    if sender.name != "apps.devices":
        return

    default_rooms = ["客厅", "厨房", "客房", "卧室", "卫生间", "阳台"]
    for room_name in default_rooms:
        room_obj, _ = Room.objects.get_or_create(name=room_name)

        def _create_if_absent(dev_name, dev_type, ctrl_val):
            if not Device.objects.filter(device_name=dev_name).exists():
                Device.objects.create(
                    device_name=dev_name,
                    device_type=dev_type,
                    room=room_obj,
                    status="offline",
                    control_value=ctrl_val
                )
                print(f"[devices] Created {dev_type}: ({dev_name}) in {room_obj.name}")

        _create_if_absent(f"{room_name}空调", "空调",   24)
        _create_if_absent(f"{room_name}加湿器", "加湿器", 50)
        _create_if_absent(f"{room_name}灯光", "灯光",   300)